//
//  HomeViewController.m
//  SuperRadio
//
//  Created by Damon on 14/12/17.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeImageView.h"
#import "NetHandler.h"
#import "FocusImages.h"
#import "Categories.h"
#import "NavigatorCollectionViewCell.h"
#import "ColumnSortingViewController.h"
#import "SettingViewController.h"
#import "SearchViewController.h"
#import "HomeInformationDetail.h"
#import "Sounds.h"
#import "SoundsCollectionViewCell.h"
#import "HotSoundDetailsViewController.h"
#import "MainPlayerViewController.h"
#import "AlbumDatailsOfList.h"
#import "JingRoundView.h"
#import "Reachability.h"

#import "AudioPlayer.h"
#import "AudioButton.h"

#import "DataBaseHandler.h"

@interface HomeViewController ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, JingRoundViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;
// 顶端照片数组
@property (nonatomic, retain) NSMutableArray *focusImagesArr;
// 分类数组
@property (nonatomic, retain) NSMutableArray *CategoriesArr;
// hotSounds数组
@property (nonatomic, retain) NSMutableArray *hotSoundsArr;
// 导航
@property (nonatomic, retain) UICollectionView *collectionView;
// 热门导航
@property (nonatomic, retain) UITableView *hotSoundsTableView;
//// 热门详情
//@property (nonatomic, retain) UITableView *hotSoundsDetailTableView;
// 选择的是哪个热门
@property (nonatomic, assign) NSInteger hotSoundsSelect;
// 数组中Sounds的个数
@property (nonatomic, assign) NSInteger hotSounds;
// Sounds的CollectionView
@property (nonatomic, retain) UICollectionView *soundsCollectionView;
//
@property (nonatomic, retain) UICollectionViewFlowLayout *flowLayoutSounds;

@property (nonatomic, retain) NSArray *arr;
// 屏幕的高
@property (nonatomic, assign) CGFloat height;
// 屏幕的宽
@property (nonatomic, assign) CGFloat width;
// 刷新
@property (nonatomic, retain) UIActivityIndicatorView *actIV;
// 刷新视图
@property (nonatomic, retain) UIView *loadingView;

// 最火的label
@property (nonatomic, retain) UILabel *hotLabel;
// 更多
@property (nonatomic, retain) UIButton *hotButton;


@property (nonatomic, assign) NSInteger cellTag;

@property (nonatomic, retain)AudioButton *audioBtn;


@property (nonatomic, retain)SoundsCollectionViewCell *cell;

@property (nonatomic, retain) MainPlayerViewController *mainPlayVC;


@property (nonatomic, retain) AudioButton *playBtn;
@property (nonatomic, assign) NSInteger playFlag;
@property (nonatomic, assign) NSInteger tableNowFlag;

@property(nonatomic, retain) UIPageControl *page;
@property(nonatomic, assign) NSInteger i;

// 定义一个字符串判断是否有网
@property (nonatomic, retain) NSString *result;


@end

@implementation HomeViewController




#pragma mark 初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.cellTag = -1;
        self.width = [UIScreen mainScreen].bounds.size.width;
        self.height = [UIScreen mainScreen].bounds.size.height;
        self.hotSoundsSelect = -1;
        self.hotSounds = 0;
        self.playFlag = -1;
        
//        // 注册一个通知中心
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        // 增加一个观察者
//        [center addObserver:self selector:@selector(ficationAction:) name:@"zuzhang" object:nil];
        
        DataBaseHandler *handler = [DataBaseHandler shareInstance];
        // 打开数据库
        [handler openDB];

        
    }
    return self;
}

//#pragma mark 通知中心要执行的方法
//- (void)ficationAction:(NSNotification *)fication
//{
//    DataBaseHandler *handler = [DataBaseHandler shareInstance];
//    // 打开数据库
//    [handler openDB:[fication.userInfo objectForKey:@"uid"]];
//    // 创建用户表
//    [handler createCollectTable];
//    
//    
//}

#pragma mark 释放
- (void)dealloc
{
    [_scrollView release];
    [_focusImagesArr release];
    [_CategoriesArr release];
    [_collectionView release];
    [_hotSoundsTableView release];
    [_hotSoundsArr release];
    [_soundsCollectionView release];
    [_flowLayoutSounds release];
    [_arr release];
    [_actIV release];
    [_loadingView release];
    [_hotLabel release];
    [_hotButton release];
    
    [super dealloc];
}


- (void)playStatuUpdate:(BOOL)playState
{
    
     self.tabBarController.selectedIndex = 0;
    _mainPlayVC = [MainPlayerViewController defaultPlayer];
     _mainPlayVC.roundView = [[self.tabBarController.tabBar subviews] objectAtIndex:1];
    if (self.navigationController.topViewController != _mainPlayVC) {
        
        if ([[_mainPlayVC.trackId stringValue] length] != 0) {
            
            CATransition *transition = [CATransition animation];
            transition.duration = 0.3f;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            transition.type = @"push";
            transition.subtype = kCATransitionFromTop;
            transition.delegate = self;
            [self.navigationController.view.layer addAnimation:transition forKey:nil];

            [self.navigationController pushViewController:_mainPlayVC animated:NO];
        }
        
        
    }

}

- (void)viewWillAppear:(BOOL)animated
{
    // 判断网络
    if ([self GetCurrntNet]) {
//        [self handleData];
//        
//        [self handleHotSoundsData];
       
        self.navigationController.navigationBarHidden = NO;
        
    }
    else {
        
        self.navigationController.navigationBarHidden = YES;
        
        UILabel *labelText = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
        labelText.center = CGPointMake(self.loadingView.center.x, self.loadingView.center.y + 30);
        labelText.text = @"请检查您的网络...";
        labelText.textAlignment = NSTextAlignmentCenter;
        labelText.font = [UIFont systemFontOfSize:15];
        [self.loadingView addSubview:labelText];
        
    }
    [self.scrollView reloadInputViews];
    
}



-(NSString*) GetCurrntNet
{
    Reachability *r = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:     // 没有网络连接
            self.result=nil;
            break;
        case ReachableViaWWAN: // 使用3G网络
            self.result=@"3g";
            break;
        case ReachableViaWiFi: // 使用WiFi网络
            self.result=@"wifi";
            break;
    }
    return self.result;
}

#pragma mark 视图载入
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    
    //设置后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if (session == nil) {
        NSLog(@"Error creating session:  %@", [sessionError description]);
    } else {
        [session setActive:YES error:nil];
    }

    self.i = 0;
    self.roundView = [[JingRoundView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 25, 0, 50, 50)];
    //    self.roundView.backgroundColor = [UIColor redColor];
    
    
    self.roundView.delegate = self;
    NSString *roundImagePath = [[NSBundle mainBundle] pathForResource:@"listen" ofType:@"jpg"];
    self.roundView.roundImage = [UIImage imageWithContentsOfFile:roundImagePath];
    self.roundView.rotationDuration = 8.0;
    self.roundView.isPlay = NO;
    
    
    AudioPlayer *player = [AudioPlayer shareInstance];
    player.roundView = self.roundView;
    
    [self.tabBarController.tabBar addSubview:self.roundView];
    
    
    
//   MainPlayerViewController *mainPlayer = [MainPlayerViewController defaultPlayer];
//    [mainPlayer showDetailInformation];
    
#pragma mark 菊花加载的View
    self.loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.loadingView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.loadingView];
    
#pragma mark 菊花加载
    self.actIV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.actIV.frame = CGRectMake(0, 0, 32, 32);
    
    // 设置菊花在视图中心位置
    self.actIV.center = self.loadingView.center;
    [self.loadingView addSubview:self.actIV];

    self.actIV.backgroundColor = [UIColor grayColor];
    // 菊花开始转动
    [self.actIV startAnimating];
    [_actIV release];

    
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.navigationController.navigationBar.translucent = YES;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(40, 5, 100, 30);
    [button setBackgroundImage:[UIImage imageNamed:@"sousuo.jpg"]forState:UIControlStateNormal];
    [button addTarget:self action:@selector(searchButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

    // 导航栏 的按钮
    self.navigationItem.titleView = button;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(clicked:)];
    
#pragma mark scrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    UIView *dianView = [[UIView alloc]initWithFrame:CGRectMake(150, 80, 200, 100)];
    dianView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:dianView];
    dianView.tag = 3001;
    
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changePage:) userInfo:nil repeats:YES];
    //首页的图片展示
    self.page = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
    self.page.numberOfPages = 6;
    [dianView addSubview:self.page];
    [dianView bringSubviewToFront:self.page];
    self.page.currentPageIndicatorTintColor = [UIColor grayColor];
    self.page.pageIndicatorTintColor = [UIColor whiteColor];
    
    [dianView release];
    self.page.backgroundColor = [UIColor clearColor];
    
    [_page release];
    
    
    [_scrollView release];
    
    // 最后面的滚动视图
    self.scrollView.backgroundColor = [UIColor whiteColor];
       self.scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 700);
    
#pragma mark 分类集合视图
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    flowLayout.itemSize = CGSizeMake(self.width / 5.0, self.width / 5.0);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    // 水平滚动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 140, self.width, self.width / 5.0 * 2) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.scrollView addSubview:self.collectionView];
    
    // 释放
    [_collectionView release];
    [flowLayout release];
    
    [self.collectionView registerClass:[NavigatorCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewReuse"];
    

#pragma mark 热门导航
//-----------------------热门导航-----------------------
    self.hotSoundsTableView = [[UITableView alloc] initWithFrame: CGRectMake(0, 170 + self.width / 5.0 * 2 + 20, self.width / 4.0 , self.width / 4 * 3 / 3 * 2 ) style:UITableViewStylePlain];
    
    self.hotSoundsTableView.delegate = self;
    self.hotSoundsTableView.dataSource = self;
    
    [self.scrollView addSubview:self.hotSoundsTableView];
    
    [self.hotSoundsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"hotSoundsTableViewReuse"];

#pragma mark 定义CollectionView
    
    self.flowLayoutSounds = [[UICollectionViewFlowLayout alloc] init];
    
    self.flowLayoutSounds.itemSize = CGSizeMake(self.width / 4.0 * 3 / 3, self.width / 4.0 * 3 / 3);
    self.flowLayoutSounds.minimumInteritemSpacing = 0;
    self.flowLayoutSounds.minimumLineSpacing = 0;
    
    self.flowLayoutSounds.headerReferenceSize = CGSizeMake(self.width / 4.0 * 3, 40);
    
    self.soundsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(self.width / 4.0, 140 + self.width / 5.0 * 2 + 20, self.width / 4.0 * 3, self.width / 4 * 3 / 3 * 2 + 50) collectionViewLayout:self.flowLayoutSounds];
    self.soundsCollectionView.backgroundColor = [UIColor whiteColor];
    self.soundsCollectionView.delegate = self;
    self.soundsCollectionView.dataSource = self;
    self.soundsCollectionView.showsHorizontalScrollIndicator = NO;
    [self.scrollView addSubview:self.soundsCollectionView];
    
    self.scrollView.contentSize = CGSizeMake(self.width, 140 + self.width / 5.0 * 2 + 20 + self.soundsCollectionView.frame.size.height);
    // 释放s
    [_soundsCollectionView release];
    [_flowLayoutSounds release];
    // 注册一个重用
    [self.soundsCollectionView registerClass:[SoundsCollectionViewCell class] forCellWithReuseIdentifier:@"flowLayoutSoundsReuse0"];
    
    [self.soundsCollectionView registerClass:[SoundsCollectionViewCell class] forCellWithReuseIdentifier:@"flowLayoutSoundsReuse1"];
    [self.soundsCollectionView registerClass:[SoundsCollectionViewCell class] forCellWithReuseIdentifier:@"flowLayoutSoundsReuse2"];
    [self.soundsCollectionView registerClass:[SoundsCollectionViewCell class] forCellWithReuseIdentifier:@"flowLayoutSoundsReuse3"];
    [self.soundsCollectionView registerClass:[SoundsCollectionViewCell class] forCellWithReuseIdentifier:@"flowLayoutSoundsReuse4"];
    [self.soundsCollectionView registerClass:[SoundsCollectionViewCell class] forCellWithReuseIdentifier:@"flowLayoutSoundsReuse5"];
    
    
    // collectionView给section注册一个view显示内容
    
    [self.soundsCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerReuse"];
    // 热门的标题
    self.hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 100, _flowLayoutSounds.headerReferenceSize.height)];
    self.hotLabel.font = [UIFont boldSystemFontOfSize:14];
    // 热门按钮
    self.hotButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.hotButton.frame = CGRectMake(_flowLayoutSounds.headerReferenceSize.width - 40 , 10, 20, 20);
    
    // 更多按钮添加图片
    
        NSString *morePath = [[NSBundle mainBundle] pathForResource:@"more" ofType:@"png"];
        [self.hotButton setBackgroundImage:[UIImage imageWithContentsOfFile:morePath] forState:UIControlStateNormal];
        
        // 设置 更多 按钮点击方法
        [self.hotButton addTarget:self action:@selector(moreButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view bringSubviewToFront:self.loadingView];
    
    
    //5:清扫
    UISwipeGestureRecognizer *soundsCollectionViewSwipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(soundsCollectionViewSwipeLeftAction:)];
    
    //清扫的方向
    soundsCollectionViewSwipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    soundsCollectionViewSwipeLeft.numberOfTouchesRequired = 1;
    [self.soundsCollectionView addGestureRecognizer:soundsCollectionViewSwipeLeft];
    
#pragma mark 调用数据处理方法
    // 处理数据
    [self handleData];
    [self handleHotSoundsData];
    // Do any additional setup after loading the view.
}
#pragma mark 轻扫方法左
- (void)soundsCollectionViewSwipeLeftAction:(UISwipeGestureRecognizer *)swipe
{
    // 如果情操方法向右 执行下面操作
    if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
        swipe.direction = UISwipeGestureRecognizerDirectionLeft;
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.soundsCollectionView.frame = CGRectMake(self.width / 4.0, 140 + self.width / 5.0 * 2 + 20, self.width / 4.0 * 3, self.width / 4 * 3 / 3 * 2 + 50);
            
            
            self.flowLayoutSounds.itemSize = CGSizeMake(self.width / 4.0 * 3 / 3, self.width / 4.0 * 3 / 3);
            
            self.flowLayoutSounds.headerReferenceSize = CGSizeMake(self.width / 4.0 * 3, 40);
            
            self.hotButton.frame = CGRectMake(_flowLayoutSounds.headerReferenceSize.width - 60 , 0, 50, _flowLayoutSounds.headerReferenceSize.height);
            
            
            self.hotSoundsTableView.frame = CGRectMake(0, self.hotSoundsTableView.frame.origin.y, self.hotSoundsTableView.frame.size.width, self.hotSoundsTableView.frame.size.height);
            
        }];
        
        
      
        
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        // 如果情操方法向左 执行下面方法
        swipe.direction = UISwipeGestureRecognizerDirectionRight;
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
           // self.hotSoundsTableView.frame = CGRectMake(- (self.width / 4), self.hotSoundsTableView.frame.origin.y, self.hotSoundsTableView.frame.size.width, self.hotSoundsTableView.frame.size.height);
            
            self.flowLayoutSounds.headerReferenceSize = CGSizeMake(self.width, 40);
            
            self.flowLayoutSounds.itemSize = CGSizeMake(self.width / 3, self.width / 3);
            
            self.soundsCollectionView.frame = CGRectMake(0, 140 + self.width / 5.0 * 2 + 20, self.width, self.width / 3 * 2 + 50);
            
           // self.hotButton.frame = CGRectMake(_flowLayoutSounds.headerReferenceSize.width - 60 , 0, 50, _flowLayoutSounds.headerReferenceSize.height);
            
             }];
        
      
        
    }
   self.hotButton.frame = CGRectMake(_flowLayoutSounds.headerReferenceSize.width - 40 , 10, 20, 20);
    
        self.scrollView.contentSize = CGSizeMake(self.width, self.soundsCollectionView.frame.origin.y + self.soundsCollectionView.frame.size.height);
}

#pragma mark 更多按钮的点击方法
- (void)moreButton:(UIButton *)button
{
    HotSoundDetailsViewController *hotSound = [[HotSoundDetailsViewController alloc] init];
    hotSound.homeInformationDetail = [self.hotSoundsArr objectAtIndex: self.hotSoundsSelect];
    // 跳转到
    [self.navigationController pushViewController:hotSound animated:YES];
    [hotSound release];
}


// 搜索按钮
- (void)searchButtonClicked:(UIButton *)button
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

//// 导航栏右侧点击按钮
//- (void)clicked: (UIBarButtonItem *)barButton
//{
//    SettingViewController *settingVC = [[SettingViewController alloc] init];
//    [self.navigationController pushViewController:settingVC animated:YES];
//    [settingVC release];
//}

- (void)changePage:(NSTimer *)time
{
    HomeImageView *imagev = (HomeImageView *)[self.view viewWithTag:3000];
    
    NSInteger a = imagev.scrollView.contentOffset.x / imagev.bounds.size.width;
    if (a == 6) {
        a = 0;
    }
    imagev.scrollView.contentOffset = CGPointMake(self.view.bounds.size.width * (a + 1), 0);
    self.page.currentPage = a;
    
}






#pragma mark 表视图的协议方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.hotSoundsSelect = indexPath.row;
    HomeInformationDetail *home = [self.hotSoundsArr objectAtIndex:indexPath.row];
    self.arr = home.soundsArr;
    self.hotLabel.text = home.title;
    [self.soundsCollectionView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.hotSoundsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hotSoundsTableViewReuse"];

        cell.textLabel.font = [UIFont systemFontOfSize:12];
        cell.textLabel.frame = cell.contentView.frame;
        [cell.textLabel sizeToFit];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.text = [[self.hotSoundsArr objectAtIndex:indexPath.row] title];
        return cell;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return self.width / 4 * 3 / 3 * 2 / 6;
    
}


#pragma mark 点击播放的按钮

- (void)playTheAudio:(AudioButton *)button
{
   
    
    
    Sounds *sound = [self.arr objectAtIndex:button.tag - 10000  * (self.hotSoundsSelect + 1)];
    sound.isPlay = YES;

    self.cellTag = button.tag;
    
   // NSLog(@"%ld",button.tag);
    _audioPlayer =  [AudioPlayer shareInstance];
    _audioPlayer.imagePath = sound.coverWebSmall;
    if ([_audioPlayer.button isEqual: button]) {
        [_audioPlayer play];
//        if (button.isPlaying == YES) {
//            self.playFlag = -1;
//            button.isPlaying = NO;
//        } else {
//            button.isPlaying = YES;
//            self.playFlag = button.tag - 10000 * (self.hotSoundsSelect + 1);
//        }
        
    } else {
       // button.isPlaying = YES;
        
         _mainPlayVC = [MainPlayerViewController defaultPlayer];
        _mainPlayVC.trackId = [[self.arr objectAtIndex:button.tag - 10000  * (self.hotSoundsSelect + 1)] id];
        [_mainPlayVC.listArr removeAllObjects];
        _mainPlayVC.index = -1;
        [_mainPlayVC showDetailInformation];
        [_audioPlayer stop];
        self.playFlag = button.tag - 10000 * (self.hotSoundsSelect + 1);
        self.tableNowFlag = self.hotSoundsSelect;
        _audioPlayer.button = button;
        
        _audioPlayer.url = [NSURL URLWithString:[[self.arr objectAtIndex:button.tag - 10000  * (self.hotSoundsSelect + 1)] playPath64]];
        
        [_audioPlayer play];
    }
    
}


#pragma mark 集合视图的协议方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView != self.collectionView) {
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerReuse" forIndexPath:indexPath];
        view.userInteractionEnabled = YES;
        [view addSubview:self.hotLabel];
        [view addSubview:self.hotButton];
        view.backgroundColor = [UIColor whiteColor];
        
        return view;
    }
    return nil;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.collectionView) {
        return self.CategoriesArr.count;
    } else {
            return self.arr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView) {
        NavigatorCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewReuse" forIndexPath:indexPath];
        
        Categories *categories = [self.CategoriesArr objectAtIndex:indexPath.item];
        cell.categories = categories;
        return cell;
    }else {
        
        
        NSString *str = [NSString stringWithFormat:@"flowLayoutSoundsReuse%ld",self.hotSoundsSelect];
        
        SoundsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:str forIndexPath:indexPath];
        
        if (self.tableNowFlag == self.hotSoundsSelect) {
          //  NSLog(@"indexpath:%d : flag: %d", indexPath.item, self.playFlag);
            
            
            if (indexPath.item == self.playFlag) {
                _audioPlayer = [AudioPlayer shareInstance];
                [cell.audioButton setProgress:_audioPlayer.button.progress];
                _audioPlayer.button = cell.audioButton;
               // _audioPlayer.isPlay = NO;
                cell.audioButton.image = [UIImage imageNamed:@"stop.png"];
                [_audioPlayer updateProgress];
                
            } else {
                [cell.audioButton setProgress:0.0f];
                cell.audioButton.image = [UIImage imageNamed:@"play.png"];
               // _audioPlayer.isPlay = YES;
                
            }
            
            
                    }
        [cell.audioButton addTarget:self action:@selector(playTheAudio:) forControlEvents:UIControlEventTouchUpInside];
        
        
        cell.audioButton.tag = indexPath.item + 10000 * (self.hotSoundsSelect + 1);
        
        cell.sounds = [self.arr objectAtIndex:indexPath.item];
        NSLog(@"%ld", cell.audioButton.tag);
        return cell;
    }
    
}
//scrollView减速停止协议
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    HomeImageView *imagev = (HomeImageView *)[self.view viewWithTag:3000];
//    
//    self.page.currentPage = imagev.scrollView.contentOffset.x / self.view.bounds.size.width;


}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionView) {
        ColumnSortingViewController *columnSortingVC = [[ColumnSortingViewController alloc] init];
        // 传值
        columnSortingVC.categories = [self.CategoriesArr objectAtIndex:indexPath.item];
        [self.navigationController pushViewController:columnSortingVC animated:YES];
        [columnSortingVC release];
    } else {
        
        
        self.cell = (SoundsCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        Sounds *sounds = [self.arr objectAtIndex:indexPath.item];
        
        AlbumDatailsOfList *dataList = [[AlbumDatailsOfList alloc]init];
        
        dataList.playUrl32 = sounds.playPath32;
        dataList.playUrl64 = sounds.playPath64;
        dataList.coverLarge = sounds.coverWebSmall;
        dataList.title = sounds.title;
        dataList.trackId = sounds.id;
        

        _mainPlayVC = [MainPlayerViewController defaultPlayer];
        //_mainPlayVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

        _mainPlayVC.albumDatail = dataList;
        _mainPlayVC.trackId = dataList.trackId;
        [_mainPlayVC.listArr removeAllObjects];
        _mainPlayVC.navi = self.navigationController;
        //[_mainPlayVC.listArr addObjectsFromArray:self.arr];
        _mainPlayVC.index = -1;
       
        _audioPlayer = [AudioPlayer shareInstance];
        
        if (![_audioPlayer.button isEqual:_cell.audioButton]) {
            
            [_audioPlayer stop];
            self.audioBtn = _cell.audioButton;

            _audioPlayer.button = _cell.audioButton;
            self.cellTag = _cell.audioButton.tag;
            _audioPlayer.url = [NSURL URLWithString:dataList.playUrl64];
            [_audioPlayer play];
            
        }
        
        
        
        [_mainPlayVC showDetailInformation];
        
        
       // self.navigationController.navigationBar.hidden = YES;
        
        CATransition *transition = [CATransition animation];
        transition.duration = 0.3f;
        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type = @"push";
        transition.subtype = kCATransitionFromTop;
        transition.delegate = self;
        [self.navigationController.view.layer addAnimation:transition forKey:nil];
        
        [self.navigationController pushViewController:_mainPlayVC animated:NO];
        
    }

}



// 获取数据
- (void)handleData
{
    // 初始化数组
    self.focusImagesArr = [NSMutableArray array];
    
    // 异步获取数据
    [NetHandler getDataWithURL:@"http://mobile.ximalaya.com/m/super_explore_index?device=iPhone&includeActivity=true&picVersion=5&scale=2" completion:^(NSData *data) {
        self.CategoriesArr = [NSMutableArray array];
        NSDictionary *sourceDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *tempImageArr = [NSArray arrayWithArray:[[sourceDic objectForKey:@"focusImages"] objectForKey:@"list"]];
        
        for (NSDictionary *tempDic in tempImageArr) {
            
            FocusImages *image = [[FocusImages alloc] initWithDictionary:tempDic];
            
            [self.focusImagesArr addObject:image];

            [image release];
        }
        
        
        HomeImageView *imageView= [[HomeImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 140) FocusImagesarr:self.focusImagesArr];
        imageView.tag = 3000;
        imageView.scrollView.delegate = self;
        NSLog(@"%@", self.focusImagesArr);
        [self.scrollView addSubview:imageView];
        UIView *vii = [self.view viewWithTag:3001];
        [self.scrollView bringSubviewToFront:vii];
        [imageView release];

        
        NSArray *tempCategoriesArr = [NSArray arrayWithArray:[[sourceDic objectForKey:@"categories"] objectForKey:@"data"]];
        
        for (NSDictionary *tempDic in tempCategoriesArr) {
            
            Categories *categories = [[Categories alloc]initWithDictionary:tempDic];
            
            [self.CategoriesArr addObject:categories];
            [categories release];
           // NSLog(@"%@", categories.orderNum);
        }
        [self.collectionView reloadData];
           }];

}
#pragma mark 获取最近热门
- (void)handleHotSoundsData
{
    
    self.hotSoundsArr = [NSMutableArray array];
    [NetHandler getDataWithURL:@"http://mobile.ximalaya.com/m/index_hotsounds?device=iPhone" completion:^(NSData *data) {
        NSDictionary *HotDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 找到categories数组
        NSArray *hotArr = [HotDic objectForKey:@"categories"];
        // 遍历数组
        for (NSDictionary *dic in hotArr) {
            // 定义一个对象
            HomeInformationDetail *homeInformationDetail = [[HomeInformationDetail alloc] initWithDictionary:dic];
            
            
            NSArray *soundsArr = [dic objectForKey:@"sounds"];
            
            for (NSDictionary *soundsdic in soundsArr) {
                // 移除对象声音数组中得所有数据
               // [homeInformationDetail.soundsArr removeAllObjects];
                // 创建一个声音对象
                Sounds *sound = [[Sounds alloc] initWithDictionary:soundsdic];
                sound.isPlay = NO;
               // 添加声音对象
                [homeInformationDetail.soundsArr addObject:sound];
                //NSLog(@"%@", sound.title);
                [sound release];
            }
            
            // 添加到数组中
            [self.hotSoundsArr addObject:homeInformationDetail];
            [homeInformationDetail release];
        }
        self.arr = [NSArray arrayWithArray:[[self.hotSoundsArr objectAtIndex:0] soundsArr]];
        // 刷新表视图, 和集合视图
        [self.hotSoundsTableView reloadData];
        [self.soundsCollectionView reloadData];
        self.hotSoundsSelect = 0;
        self.hotLabel.text = [[self.hotSoundsArr objectAtIndex:0] title];
        // 加载停止
        [self.actIV stopAnimating];
        // 把
        [self.view sendSubviewToBack:self.loadingView];
    }];
  
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
